// types.d.ts 或内联定义
interface SSEData {
  id?: string;
  event?: string;
  data: any;
  retry?: number;
}

export class MockSSEResponse {
  private controller!: ReadableStreamDefaultController<Uint8Array>;
  private encoder = new TextEncoder();
  private stream: ReadableStream<Uint8Array>;
  private delay: number;

  constructor(
    private chunks: SSEData[], // 改为接收分块数据数组
    delay: number = 300,
    private simulateErrorAt?: number // 在第几个 chunk 抛错，undefined 表示不抛错
  ) {
    this.delay = delay;

    this.stream = new ReadableStream({
      start: (controller) => {
        this.controller = controller;
        this.pushChunks();
      },
      cancel: () => {
        console.log("SSE stream canceled");
      },
    });
  }

  private async pushChunks(index = 0): Promise<void> {
    if (index >= this.chunks.length) {
      this.controller.close();
      return;
    }

    // 模拟网络错误
    if (this.simulateErrorAt === index) {
      try {
        // 发送错误响应前先结束流
        this.controller.error(new Error("Simulated network error"));
      } finally {
        this.controller.close();
      }
      return;
    }

    const chunk = this.chunks[index];
    const lines = [`data: ${JSON.stringify(chunk)}`, "", ""].join("\n"); // SSE 格式：data: ...\n\n

    this.controller.enqueue(this.encoder.encode(lines));

    // 递归发送下一块
    setTimeout(() => {
      this.pushChunks(index + 1);
    }, this.delay);
  }

  getResponse(): Promise<Response> {
    return new Promise((resolve) => {
      // 模拟初始网络延迟
      setTimeout(() => {
        resolve(
          new Response(this.stream, {
            headers: {
              "Content-Type": "text/event-stream",
              "Cache-Control": "no-cache",
              Connection: "keep-alive",
            },
          })
        );
      }, this.delay / 2);
    });
  }
}
